import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Table, Grid } from 'semantic-ui-react'
import Styled from 'styled-components'
import { BasicButton, PrimaryButton } from 'components/Button'
import { validForm as validFormDuck } from 'ducks'
import { push, go, replace } from 'connected-react-router'
import { Mutation } from 'react-apollo'

const TableCell = Styled(Table.Cell)`
  padding-top: 1.2em!important;
`

const SectionRow = Styled.div`
  margin-bottom: 1em;
`
class SubmitAction extends Component {
  componentDidMount = () => {}

  mergeVariables = (variables, getFunc, values) => Object.assign({}, variables, getFunc(values))

  render() {
    const {
      submit,
      cancle,
      isFormValid,
      cancleAction,
      values,
      redirectAction,
      replace,
      redirect,
      red,
    } = this.props
    let variables
    if (isFormValid) {
      variables = this.mergeVariables(submit.variables, submit.getVariables, values)
    }
    console.log(red)
    return (
      <Grid.Row>
        <Grid.Column>
          <Table basic="very" size="large">
            <Table.Row>
              <TableCell />
              <TableCell textAlign="right">
                <SectionRow>
                  {cancle && (
                    <BasicButton content={cancle.text} onClick={() => cancleAction(cancle.url)} />
                  )}
                  {submit && (
                    <Mutation
                      mutation={submit.mutation}
                      onCompleted={(data) => {
                        replace(submit.success(data))
                      }}
                    >
                      {(addTodo, { data, loading, error }) => (
                        <PrimaryButton
                          disabled={!isFormValid}
                          content={submit.text}
                          color={red ? 'red' : undefined}
                          onClick={() => addTodo({ variables })}
                        />
                      )}
                    </Mutation>
                  )}
                </SectionRow>
              </TableCell>
            </Table.Row>
          </Table>
        </Grid.Column>
      </Grid.Row>
    )
  }
}

const mapStateToProps = (state, ownProps) => ({
  isFormValid: validFormDuck.selectors.isFormValid(state, ownProps.validFields),
  values: validFormDuck.selectors.values(state),
})

const mapDispatchToProps = {
  cancleAction: url => push(url),
  redirectAction: () => go(0),
  replace: url => push(url),
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(SubmitAction)
